package com.canbot.u05.activity.training;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.bean.TrainingTask;
import com.canbot.u05.bean.training.Step;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.ConstUtils;
import com.canbot.u05.utils.FileUtil;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.utils.Utils;
import com.canbot.u05.view.TrainingEditTextDialog;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 培训主持------任务编辑界面
 */
public class StaffTrainingActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private static final String TAG = "StaffTrainingActivity";

        private final int STAFFTRAINING_ADD = 1;

        private final int DELETEHINT = 2;

        private final int ACTIONMOVEHINT = 3;

        private final int HINTFINISH = 4;

        private TextView mTextTitle;

        private Button mBtBack;

        private Button mBtSave;

        private RecyclerView mRcvStaffTrainingAdd;

        private ImageView mIvStaffTrainingDel;

        private List<TrainingTask> mIntss;

        private ItemTouchHelper itemTouchHelper;

        private PostArticleImgAdapter postArticleImgAdapter;

        private String taskName;

        private Dialog dialogLoading;

        private TrainingEditTextDialog editTextDialog;

        private List<String> taskList;

        private String tasks;

        private String addtaskName;

        private SharedPreferences sp;

        private boolean updateStep = false;

        private boolean isCreate = false;

        private Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what){
                                case STAFFTRAINING_ADD:
                                        if (TextUtils.isEmpty(taskName)) {
                                                mIntss.clear();
                                                mIntss.add(new TrainingTask(1,"添加任务步骤", R.drawable.stafftraining_add, ""));
                                                postArticleImgAdapter.notifyDataSetChanged();
                                                return;
                                        }
                                        initupdateData(taskName);
                                        break;
                                case ACTIONMOVEHINT:
                                        setAnimeImage(ConstUtils.SD_PathMoveHint,
                                                ACTIONMOVEHINT, 180);
                                        break;
                                case DELETEHINT:
                                        setAnimeImage(ConstUtils.SD_PathDelHint,
                                                DELETEHINT, 180);
                                        break;
                                case HINTFINISH:
                                        mHandler.removeMessages(DELETEHINT);
                                        imageViewHint.setVisibility(View.GONE);
                                        initupdateData("step");
                                        break;
                        }
                }
        };

        private ImageView imageViewHint;

        private List<Step> stepList;

        private boolean isMove = false;

        private MyCallBack myCallBack;

        private boolean isDelUpd=false;

        private Bitmap[] bitmap = null;

        private int currentIndex;

        private int isClick = -1;

        private StringBuffer micPath = new StringBuffer();

        int hintImgCount;

        int delImgCount;

        private List<Integer> imageList;

        public static final int REQ_CODE_OVERLAY = 250;

        private ToastTools toastTools;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_training_host_staff_training);
                toastTools = ToastTools.newInstance(this);
                taskName = getIntent().getStringExtra("taskName");

                tasks = getIntent().getStringExtra("stepList");
                taskList = JSONArray.parseArray(tasks, String.class);
                sp = getSharedPreferences("training_host", Context.MODE_PRIVATE);
                mIntss = new ArrayList<>();

                hintImgCount = FileUtil.getFilesLength(ConstUtils.SD_PathMoveHint,
                        ".png");
                delImgCount = FileUtil.getFilesLength(ConstUtils.SD_PathDelHint,
                        ".png");

                postArticleImgAdapter = new PostArticleImgAdapter(this, mIntss);

                if (!TextUtils.isEmpty(taskName)) {
                        allTesk(taskName);
                }
                else {
                        mHandler.sendEmptyMessageDelayed(STAFFTRAINING_ADD,0);
                }
                //检查权限WindowManager 6.0权限检测
                if (!Settings.canDrawOverlays(this)) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                        startActivityForResult(intent, REQ_CODE_OVERLAY);
                        return;
                }
                initView();

                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.TRAINING_DIR + "rwbjyd_pxzc_u05_001.wav");
                MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "14");
        }
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (requestCode == REQ_CODE_OVERLAY) {
                        if (Settings.canDrawOverlays(this)) {
                                Log.e("onActivityResult", "resultCode:" + true);
                                initView();
                        }
                        else {
                                toastTools.showText(getString(R.string.permission_denied));
                                finish();
                        }
                        return;
                }
        }
        private void initView() {
                Logger.e(TAG, "initView----initView");

                isCreate = true;

                //TODO
                mTextTitle = (TextView) findViewById(R.id.text_title);
                mBtBack = (Button) findViewById(R.id.bt_back);
                mBtSave = (Button) findViewById(R.id.bt_save);
                mTextTitle.setText(taskName);
                mBtBack.setOnClickListener(this);
                mBtSave.setOnClickListener(this);

                imageViewHint = (ImageView) findViewById(R.id.activity_training_action_hint);
                imageViewHint.setOnClickListener(this);

                mRcvStaffTrainingAdd = (RecyclerView) findViewById(R.id.rcv_staffTraining_add);
                mRcvStaffTrainingAdd = (RecyclerView) findViewById(R.id.rcv_staffTraining_add);
                mIvStaffTrainingDel = (ImageView) findViewById(R.id.iv_staffTraining_del);

                if(TextUtils.isEmpty(taskName)){
                        myCallBack= new MyCallBack(postArticleImgAdapter, mIntss, StaffTrainingActivity.this, sp,"step");
                }else{
                       myCallBack = new MyCallBack(postArticleImgAdapter, mIntss, StaffTrainingActivity.this, sp,taskName);
                }
                myCallBack.setDelImage(mIvStaffTrainingDel,R.drawable.train_del_selector);
                itemTouchHelper = new ItemTouchHelper(myCallBack);
                itemTouchHelper.attachToRecyclerView(mRcvStaffTrainingAdd);//绑定RecyclerView

                mRcvStaffTrainingAdd.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
                mRcvStaffTrainingAdd.setAdapter(postArticleImgAdapter);
                //事件监听
                mRcvStaffTrainingAdd.addOnItemTouchListener(new OnRecyclerItemClickListener(mRcvStaffTrainingAdd) {

                        @Override
                        public void onItemClick(RecyclerView.ViewHolder vh) {
                                if (vh.getLayoutPosition() == mIntss.size() - 1) {
                                        // TODO: 2017/12/25  增加步骤
                                        isDelUpd=true;
                                        Intent intent = new Intent(StaffTrainingActivity.this, TrainingHostImageSettingActivity.class);
                                        if (TextUtils.isEmpty(taskName)) {
                                                if(!updateStep){
                                                        intent.putExtra("isFirst", "isFirst");
                                                }else{
                                                        intent.putExtra("isFirst", "");
                                                }
                                                startActivity(intent);
                                        }
                                        else {
                                                intent.putExtra("taskName", taskName);
                                                startActivity(intent);
                                        }


                                }
                                else {

                                        isDelUpd=true;
                                        // TODO: 2017/12/25
                                        Intent intent = new Intent(StaffTrainingActivity.this, TrainingTaskSettingActivity.class);
                                        intent.putExtra("stepName", mIntss.get(vh.getAdapterPosition()).getText());
                                        intent.putExtra("stepId", vh.getAdapterPosition());
                                        if (!TextUtils.isEmpty(taskName)) {
                                                intent.putExtra("taskName", taskName);
                                        }
                                        else {
                                                intent.putExtra("taskName", "");
                                                intent.putExtra("stepData", sp.getString("step", null));
                                        }
                                        startActivity(intent);
                                        overridePendingTransition(R.anim.face_zoom_enter,
                                                R.anim.face_zoom_exit);

                                }
                        }

                        @Override
                        public void onItemLongClick(RecyclerView.ViewHolder vh) {
                                //如果item不是最后一个，则执行拖拽
                                if (vh.getLayoutPosition() != mIntss.size() - 1) {
                                        isDelUpd=true;
                                        itemTouchHelper.startDrag(vh);
                                        myCallBack.showWindowView(vh.itemView);
                                }
                        }
                });

                imageList = new ArrayList<>();
                for(int i =0;i<100;i++){
                        imageList.add(R.drawable.stafftraining_bg1);
                        imageList.add(R.drawable.stafftraining_bg2);
                        imageList.add(R.drawable.stafftraining_bg3);
                        imageList.add(R.drawable.stafftraining_bg4);
                }

        }

        /**
         * 设置动画图片
         */
        private void setAnimeImage(String imgDir, int stateImage, long time ) {

                if (bitmap != null && imageViewHint != null) {

                        if (currentIndex >= bitmap.length) {
                                currentIndex = 0;
                        }
                        if (micPath != null && micPath.length() > 0) {
                                micPath.delete(0, micPath.length());
                        }
                        micPath.append(currentIndex).append(".png");
                        bitmap[currentIndex] = Utils.fromSD(imgDir, micPath.toString());
                        micPath.delete(0, micPath.length());
                        if (bitmap[currentIndex] != null && !bitmap[currentIndex].isRecycled()) {
                                imageViewHint.setImageBitmap(bitmap[currentIndex]);
                        }
                        if (currentIndex > 0) {
                                if (null != bitmap[(currentIndex - 1)]) {
                                        bitmap[(currentIndex - 1)].recycle();
                                        bitmap[(currentIndex - 1)] = null;
                                }
                        }
                        currentIndex++;
                        mHandler.sendEmptyMessageDelayed(stateImage, time);
                }
        }


        @Override
        protected void onResume() {
                super.onResume();

                if (TextUtils.isEmpty(taskName)) {

                        String stepList = sp.getString("step", null);
                        Logger.e(TAG,stepList+"----------onResume");
                        if (!TextUtils.isEmpty(stepList)) {
                                updateStep = true;
                        }
                        if (updateStep && isClick<0) {
                                Logger.e(TAG,isClick+"----------onResume");
                                //显示提示界面
                                imageViewHint.setVisibility(View.VISIBLE);
                                bitmap = new Bitmap[ hintImgCount + 1];
                                currentIndex = 0;
                                mHandler.sendEmptyMessage(ACTIONMOVEHINT);

                                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.TRAINING_DIR + "bzts_pxzc_u05_001.wav");
                                MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "32");
                                return;
                        }
                        initupdateData("step");
                        return;
                }

                if(updateStep){
                        initupdateData("step");
                        return;
                }
                if(!TextUtils.isEmpty(taskName) && isCreate){
                        isCreate = false;
                        initupdateData(taskName);
                }
                initupdateData(taskName);
        }

        /**
         * 刷新修改步骤的数据
         */
        private void initupdateData(String text) {

                String stepList = sp.getString(text, null);

                if(TextUtils.isEmpty(stepList)){
                        mHandler.sendEmptyMessageDelayed(STAFFTRAINING_ADD,0);
                        return;
                }

                List<Step> stepOld = JSON.parseArray(stepList, Step.class);
                Logger.e(TAG, taskName + "存的本有的步骤数----" + stepOld.size());

                mIntss.clear();

                if (stepOld.size() == 0) {
                        mIntss.add(new TrainingTask(1,"添加任务步骤", R.drawable.stafftraining_add, ""));
                }
                else {

                        for (int i = 0; i < stepOld.size(); i++) {
                                        int j = i + 1;
                                        mIntss.add(new TrainingTask(i,"任务步骤" + j, imageList.get(i), j + ""));

                        }
                        mIntss.add(new TrainingTask(stepOld.size(),"添加任务步骤", R.drawable.stafftraining_add, ""));
                        updateStep = true;
                        postArticleImgAdapter.setmDatas(mIntss);
                        Logger.e(TAG, "mIntss.size()----" + mIntss.size());
                }
                postArticleImgAdapter.notifyDataSetChanged();
        }

        /**
         * 获取某个任务的所有步骤
         */
        private void allTesk(final String name) {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(StaffTrainingActivity.this, getResources().getString(R.string.request));
                dialogLoading.show();
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("type", 1);
                hasMap.put("taskName", name);
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "trainPresided", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                isCreate = true;
                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                                final String msg;

                                if (strMsgBean.getRc() != 0) {
                                        msg = strMsgBean.getMsg();
                                }
                                else {
                                        msg = "数据加载成功";
                                }
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {

                                                toastTools.showText(msg);

                                                if (strMsgBean.getRc() == 0) {
                                                        dialogLoading.dismiss();
                                                        stepList = JSON.parseArray(strMsgBean.getResult().toString(), Step.class);
                                                        sp.edit().putString(taskName, JSON.toJSONString(stepList)).apply();

                                                        Logger.e(TAG, "stepList" + stepList.toString() + taskName);
                                                        mHandler.sendEmptyMessageDelayed(STAFFTRAINING_ADD,0);
                                                }
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                isCreate = false;
                                Logger.e("StaffTrainingActivity", "onFailure");
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                dialogLoading.dismiss();
                                                toastTools.showText( "网络异常，请检查网络！");
                                        }
                                });
                        }
                });

        }

        @Override
        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.bt_back:
                                editTextDialog = new TrainingEditTextDialog(StaffTrainingActivity.this, 2);
                                editTextDialog.setTitle("退出后将清空当前数据", "是否确定退出");
                                editTextDialog.setOnNegativeListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                                editTextDialog.dismiss();
                                        }
                                });
                                editTextDialog.setOnPositiveListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                                editTextDialog.dismiss();
                                                if(sp.contains("step")){
                                                        sp.edit().remove("step").apply();
                                                }

                                                if(sp.contains(taskName)){
                                                        sp.edit().remove(taskName).apply();
                                                }
                                                finish();
                                        }
                                });
                                editTextDialog.show();
                                break;
                        case R.id.bt_save:
                                if (!updateStep) {
                                        Toast.makeText(this, "请先去设置数据", Toast.LENGTH_SHORT).show();
                                        return;
                                }

                                if (TextUtils.isEmpty(taskName)) {

                                        MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.TRAINING_DIR + "bcrwts_pxzc_u05_001.wav");
                                        MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "12");

                                        editTextDialog = new TrainingEditTextDialog(StaffTrainingActivity.this, 1);
                                        editTextDialog.setOnNegativeListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View view) {
                                                        editTextDialog.dismiss();
                                                }
                                        });
                                        editTextDialog.setOnPositiveListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View view) {
                                                        String stepList = sp.getString("step", null);
                                                        List<Step> stepOld = JSON.parseArray(stepList, Step.class);

                                                        editTextDialog.dismiss();
                                                        addtaskName = editTextDialog.getEditText().getText().toString();
                                                        if (TextUtils.isEmpty(addtaskName.trim())) {
                                                                toastTools.showText("命名不能为空!");
                                                                return;
                                                        }
                                                        //重复命名提示
                                                        for (int i = 0; i < taskList.size(); i++) {
                                                                if (taskList.get(i).equals(addtaskName.trim())) {
                                                                        toastTools.showText("已存在,请重新命名!");
                                                                        return;
                                                                }
                                                        }
                                                        if (addtaskName.length() > 8) {
                                                                toastTools.showText("最大不能超过8个字");
                                                                return;
                                                        }
                                                        editTextDialog.dismiss();
                                                        addTask(addtaskName, stepOld, false);

                                                }
                                        });
                                }
                                else {
                                        editTextDialog = new TrainingEditTextDialog(StaffTrainingActivity.this, 2);
                                        editTextDialog.setTitle("是否将更改保存到此任务中", "");
                                        editTextDialog.setOnNegativeListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View view) {
                                                        editTextDialog.dismiss();
                                                }
                                        });
                                        editTextDialog.setOnPositiveListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View view) {
                                                        editTextDialog.dismiss();

                                                        String stepList = sp.getString(taskName, null);
                                                        List<Step> stepOld = JSON.parseArray(stepList, Step.class);

                                                        addTask(taskName, stepOld, true);

                                                }
                                        });

                                }

                                editTextDialog.show();
                                break;
                        case R.id.activity_training_action_hint:
                                if (!isMove) {
                                        mHandler.removeMessages(ACTIONMOVEHINT);
                                        imageViewHint.setVisibility(View.VISIBLE);
                                        bitmap = new Bitmap[delImgCount + 1];
                                        isClick ++;
                                        currentIndex = 0;
                                        mHandler.sendEmptyMessage(DELETEHINT);
                                        MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.TRAINING_DIR + "bzts_pxzc_u05_002.wav");
                                        MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "15");
                                        isMove = true;
                                        return;
                                }
                                mHandler.sendEmptyMessage(HINTFINISH);
                                break;
                        default:
                                break;
                }

        }

        /**
         * 添加某个任务
         */
        private void addTask(String name, List<Step> steps, boolean isUpdate) {

                Logger.e(TAG, "steps.toString()" + steps.toString());
                dialogLoading = LoadingDialogUtils.createLoadingDialog(StaffTrainingActivity.this, getResources().getString(R.string.request));
                dialogLoading.show();
                HashMap<String, Object> hasMap = new HashMap<>();
                if (isUpdate) {
                        hasMap.put("type", 3);
                }
                else {
                        hasMap.put("type", 2);
                }
                hasMap.put("taskName", name);
                hasMap.put("steps", JSON.toJSONString(steps));

                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "trainPresided", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                                final String msg;

                                if (strMsgBean.getRc() != 0) {
                                        msg = strMsgBean.getMsg();
                                }
                                else {
                                        msg = "保存成功！";
                                }

                                if(sp.contains("step")){
                                        sp.edit().remove("step").apply();
                                }

                                if(sp.contains(taskName)){
                                        sp.edit().remove(taskName).apply();
                                }

                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {

                                                dialogLoading.dismiss();
                                                toastTools.showText(msg);
                                                if (strMsgBean.getRc() == 0) {
                                                        MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.TRAINING_DIR + "bccg_pxzc_u05_001.wav");
                                                        MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "18");
                                                        finish();
                                                }
                                                else {
                                                        MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.TRAINING_DIR + "bcsb_pxzc_u05_001.wav");
                                                        MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "28");
                                                }

                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                Logger.e("StaffTrainingActivity", "onFailure");
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                dialogLoading.dismiss();
                                                toastTools.showText("网络异常，请检查网络！");
                                        }
                                });
                        }
                });

        }
}
